<script setup lang="ts">
import {UploadFilled} from '@element-plus/icons-vue'
import List from "./list.vue";
import {ref} from 'vue'
import {baseURL} from "../service";
import {ElMessage} from "element-plus";
import {upload} from "../service/http.ts";


const dialogFormVisible = ref(false)
const formLabelWidth = '5rem'

const fileInfo = ref({
  name: "",
  path: "",
})

const save = () => {
  if (fileInfo.value.path === "") {
    ElMessage.error("文件未上传")
    return
  }
  // const dataFrom = JSON.parse(JSON.stringify(fileInfo.value))
  upload(fileInfo.value)
      .then((res: any) => {
        if (res.data.code === 200) {
          ElMessage.success("添加成功");
        }
        dialogFormVisible.value = false;
      })
}

// 成功回调
const handleUploadSuccess = (res: any) => {
  const {code, data, msg} = res;
  if (code === 200) {
    fileInfo.value.path = data;
    ElMessage.success("上传成功");
  } else {
    ElMessage.warning(msg);
  }
};

// 文件上传失败时的钩子
const handleUploadError = () => {
  ElMessage.error("网络错误，请稍后再试");
};

</script>

<template>
  <el-container style="width: 100vw;height: 100vh">
    <el-header style="width: 100%;display: flex;align-items: center">
      <el-button @click="dialogFormVisible=true">添加</el-button>
    </el-header>
    <el-main style="position: relative;width: 100%;height: 80%">
      <List></List>
    </el-main>
  </el-container>

  <el-dialog v-model="dialogFormVisible" title="添加模板" width="500" center align-center>
    <el-form :model="fileInfo">
      <el-form-item label="文件名" :label-width="formLabelWidth" required>
        <el-input v-model="fileInfo.name" autocomplete="off"/>
      </el-form-item>
      <el-upload
          class="upload-demo"
          drag
          :action="baseURL+'/file/upload'"
          :show-file-list="false"
          multiple
          method="post"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
      >
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text">
          拖动文件或者<em>点击上传</em>
        </div>
      </el-upload>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>

</style>